// import { useRouter } from "vue-router";
// const router = useRouter();

import { useDebounceFn, useThrottleFn } from "@vueuse/core";
import { http } from "@/utils/http";
import clipboard3 from "vue-clipboard3";

// 解构方法
const { toClipboard } = clipboard3();
import { showToast, showLoadingToast, closeToast, showImagePreview, showSuccessToast, showFailToast } from "vant";
import router from "@/router/index";
import dayjs from "dayjs";
import isBetween from "dayjs/plugin/isBetween";
import calendar from "dayjs/plugin/calendar";
import duration from "dayjs/plugin/duration";
import updateLocale from "dayjs/plugin/updateLocale";
import "dayjs/locale/zh-cn";
// @ts-ignore
import NativeShare from "nativeshare";

dayjs.extend(isBetween);
dayjs.extend(calendar);
dayjs.extend(duration);
dayjs.extend(updateLocale);

dayjs.locale("zh-cn");
const useDebounce = useDebounceFn(() => "response", 500);
const useThrottle = useThrottleFn(() => "response", 1000);

import setPageTitle from "@/utils/set-page-title";
const gotoBack = () => {
  router.back();
};
const onCopyFn = (text: any) => {
  try {
    toClipboard(text);
    showSuccessToast("复制成功");
  } catch (err) {
    console.error(err);
    showFailToast("复制失败，请手动复制");
  }
};
const gotoPath = (path: any) => {
  if (!path) return showToast("暂时还没有页面");
  // if (!localStorage.getItem("ageStatement")) {
  //   router.push("/ageStatement");
  //   return;
  // }
  // if (!localStorage.getItem("disclaimers")) {
  //   router.push("/disclaimers");
  //   return;
  // }
  router.push(path);
};
const gotoPathReplace = (path: any) => {
  if (!path) return showToast("暂时还没有页面");
  // if (!localStorage.getItem("ageStatement")) {
  //   router.replace("/ageStatement");
  //   return;
  // }
  // if (!localStorage.getItem("disclaimers")) {
  //   router.replace("/disclaimers");
  //   return;
  // }
  router.replace(path);
};
const JumpLink = (path: any) => {
  if (!path) return showToast("暂时还没有页面");
  if (!path.includes("http")) return showToast("链接异常，请联系客服");
  window.open(path);
};

const getBase64Image = (img: any) => {
  const canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  const ctx = canvas.getContext("2d") as any;
  ctx.fillStyle = "#fff";
  ctx.drawImage(img, 0, 0, img.width, img.height);
  const dataURL = canvas.toDataURL("image/jpeg"); // 可选其他值 image/jpeg
  return dataURL;
};

// 图片转base64
const imageConversion = (url: any) => {
  return new Promise(resolve => {
    const img = new Image();
    img.setAttribute("crossOrigin", "anonymous"); // 解决iOS微信端报错 securityError...insource啥的、
    img.crossOrigin = "Anonymous";
    img.onload = () => {
      // 一定要在onload后去压缩转码，否则可能因图片未加载传入，报错或者undefind之类的
      const base64 = getBase64Image(img);
      resolve(base64);
    };
    img.src = `${url}?v=${Math.random()}`; // 处理缓存
  });
};

const gotoMapFn = (latitude: any, longitude: any, detail: any) => {
  console.log(latitude, longitude, detail);
  // 设置经纬度和其他参数
  // var latitude = 37.7749; // 纬度
  // var longitude = -122.4194; // 经度
  const label = "S"; // 位置标签
  const query = "Google+Campus"; // 查询字符串
  // 构建URL
  const url = "comgooglemaps://?center=" + latitude + "," + -longitude + "&zoom=14&views=traffic&q=" + encodeURIComponent(detail);
  // 在iOS设备上使用的URL
  // const iosUrl = "https://maps.google.com/maps?daddr=" + latitude + "," + longitude + "&amp;ll=" + detail;
  const iosUrl = `https://www.google.com/maps?q=${latitude},${longitude}+${detail}`;
  // 跳转到URL
  window.location.href = iosUrl;
  // return;
  // JumpServiceLink(
  //   // 高德
  //   // `http://maps.googleapis.com/maps/api/staticmap?center=${latitude},${longitude}&zoom=14&size=400x300&sensor=false`
  //   // `http://maps.google.com/map/api/staticmap?center=${latitude},${longitude}&size=640*640&sensor=true`
  //   `https://uri.amap.com/marker?position=${longitude},${latitude}&name=${detail}`
  //   // `http://api.map.baidu.com/marker?location=${latitude},${longitude}&name==${detail}&output=html`
  // );
};
const JumpServiceLink = (path = "") => {
  if (!path) {
    path = `https://api.whatsapp.com/send/?phone=85262891140&text&type=phone_number&app_absent=0`;
  }
  console.log(path);
  window.open(path);
};

const JumpServiceCall = (phoneNumber = "+852 62891140") => {
  // 构建拨号链接 [ 电话客服]
  const callLink = `tel:${`${phoneNumber}`}`;
  // 跳转到拨号页面
  window.location.href = callLink;
};
// pub-use.ts
// 获取assets静态资源
const getAssetsFile = (url: string) => {
  // console.log(new URL(`../icons/${url}`, import.meta.url).href);
  // debugger;
  return new URL(`../${url}`, import.meta.url).href;
};

const afterRead = (file: any) => {
  showLoadingToast("上传中");
  console.log(file, "1222222");
  const files = file.file;
  const formData = new FormData();
  formData.append("name", files.name);
  formData.append("fileData", files);
  console.log(formData, "forms");
  http.post(`h5/upload/image`, { fileData: formData }).then(({ code, data }: any) => {
    console.log(code, data);
  });
};
const ImagePreview = (file: any) => {
  console.log(file);
  showImagePreview(file);
};
const timeComparison = (time: any) => {
  console.log(time, "1");
  // 假设 now 是当前时间，otherTime 是另一个时间
  const now = dayjs();
  const otherTime = dayjs(time); // 示例时间
  // 计算两个时间之间的差值
  const difference = otherTime.diff(now, "hours");
  // 判断差值是否小于3
  const isLessThan3Hours = difference < 3;
  console.log("时间小于3小时：", isLessThan3Hours); // 如果相差小于3小时，输出 true，否则输
};

const isInTimeWithin = (start_time: any, end_time: any) => {
  // 判断是否在时间内
  console.log(start_time, end_time, "1");
  // 假设 now 是当前时间，otherTime 是另一个时间
  const now = dayjs();
  // 判断当前时间是否在两个时间之间
  const isNowBetweenTimes = now.isBetween(start_time, end_time);
  console.log(isNowBetweenTimes); // 如果当前时间在startTime和endTime之间，将输出true，否则输出false
  return isNowBetweenTimes;
};
const timeCalendar = (start_time: any) => {
  return dayjs(start_time).calendar(null, {
    sameDay: "[今天] HH:mm ", // The same day ( Today at 2:30 AM )
    nextDay: "[明天] HH:mm ", // The next day ( Tomorrow at 2:30 AM )
    nextWeek: "dddd", // The next week ( Sunday at 2:30 AM )
    lastDay: "[昨天]", // The day before ( Yesterday at 2:30 AM )
    lastWeek: "[Last] dddd", // Last week ( Last Monday at 2:30 AM )
    sameElse: "YYYY-MM-DD" // Everything else ( 7/10/2011 )
  });
};
const TinyMceFormatFn = (data: any) => {
  return data.replace(/<img/g, "<img style='max-width:100%;height:auto;display: block;'").replace(/<video/g, "<video style='max-width:100%;height:auto;display: block;'");
  // 格式化数据
  // 目标时间，这里以一个特定日期为例
};

const JoinDayFn = (time: any) => {
  const targetTime = time;
  // 解析目标时间
  const targetMoment = dayjs(targetTime);
  // 获取当前时间
  const now = dayjs();
  // 计算时间差
  // 计算过去时间与现在的天数差
  const daysAgo = targetMoment.diff(now, "days");
  console.log(`过去的日期与现在的天数差是: ${daysAgo.toString().split("-")[1]} 天`);
  return daysAgo.toString().split("-")[1];
};
const nativeShareFn = (title: any, link: any) => {
  console.log("点击分享", link);
  const nativeShare = new NativeShare();
  const shareData = {
    title: "G-EmptyProject",
    desc: `${title}`,
    // // 如果是微信该link的域名必须要在微信后台配置的安全域名之内的。
    link: `${link}`,
    // icon: "https://image.fulllinkai.com/202404/17/428d349a70219c3916c3e62517ab14a6.png",
    // 不要过于依赖以下两个回调，很多浏览器是不支持的
    icon: "https://image.fulllinkai.com/202404/17/428d349a70219c3916c3e62517ab14a6.png",
    from: "@fa-ge",
    success: function () {
      showSuccessToast("分享成功");
    },
    fail: function () {
      // showFailToast("fail");
    }
  };
  nativeShare.setShareData(shareData);

  try {
    nativeShare.call("wechatFriend"); //
    // 如果是分享到微信则需要 nativeShare.call('wechatFriend')
    // 类似的命令有
    //  default 默认，调用起底部的分享组件，当其他命令不支持的时候也会调用该命令
    //  wechatTimeline 分享到朋友圈
    //  wechatFriend 分享给微信好友
    //  qqFriend 分享给QQ好友
    //  qZone 分享到QQ空间
    //  weibo 分享到微博
    // alert("成功");
  } catch (err) {
    // 如果不支持，你可以在这里做降级处理
    // alert(err);
  }
};
export {
  gotoBack,
  gotoPath,
  afterRead,
  getAssetsFile,
  useDebounce,
  useThrottle,
  setPageTitle,
  JumpLink,
  JumpServiceLink,
  onCopyFn,
  useThrottleFn,
  JumpServiceCall,
  gotoMapFn,
  ImagePreview,
  timeComparison,
  isInTimeWithin,
  timeCalendar,
  JoinDayFn,
  imageConversion,
  TinyMceFormatFn,
  nativeShareFn,
  gotoPathReplace
};
